package com.gopay.scheduler.service.jobmonitor.impl;

import com.gopay.common.constants.cust.SMSType;
import com.gopay.scheduler.GopaySchedulerFactory;
import com.gopay.scheduler.common.SendMsg;
import org.quartz.*;
import org.quartz.impl.StdScheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import sun.awt.TracedEventQueue;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by liyang on 2017/3/23.
 */
@Component("cronJobListener")
public class CronTriggerListener implements TriggerListener ,ApplicationContextAware {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private ApplicationContext applicationContext;

    @Resource(name = "sendMsg")
    private SendMsg sendMsg;

    @Value("#{webProperties['jobCron.sms.switch']}")
    private String jobCronSwitch;

    private static final String SWITCH_ON = "on";

    @Value("#{webProperties['jobCron.recvMobile']}")
    private String recvMobile;

    @Resource(name = "allStartQuertz")
    private StdScheduler stdScheduler ;

    private static Set<Trigger> errorTrigger = new LinkedHashSet<>();

    @Override
    public String getName() {
        return "CronJobListener";
    }

    @Override
    public void triggerFired(Trigger trigger, JobExecutionContext jobExecutionContext) {
        try{
            logger.info("***********开发触发：" + trigger.getJobKey().getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean vetoJobExecution(Trigger trigger, JobExecutionContext jobExecutionContext) {
        return false;
    }

    @Override
    public void triggerMisfired(Trigger trigger) {
        try{
        if(stdScheduler == null)
            stdScheduler = (StdScheduler) applicationContext.getBean("allStartQuertz");
        String jobName = trigger.getJobKey().getName();
                try {
                    if(stdScheduler.getTriggerState(trigger.getKey()) != Trigger.TriggerState.NORMAL) {
                        logger.info(String.format("*****************%s 调度失败！！**********", jobName));
                        if(SWITCH_ON.equals(jobCronSwitch))
                            sendMsg.sendSms(recvMobile, String.format("%s Job在%s调度异常（生产），请您处理！",jobName, new Date()), SMSType.OTHER_SMS);
                        else
                            logger.info(String.format("cron预警短信已关闭：%s Job在%s调度异常，请您处理！",jobName, new Date()));
                    }
                } catch (SchedulerException e) {
                    e.printStackTrace();
                }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void triggerComplete(Trigger trigger, JobExecutionContext jobExecutionContext, Trigger.CompletedExecutionInstruction completedExecutionInstruction) {
        try {
            String jobName = trigger.getJobKey().getName();
            if (SWITCH_ON.equals(jobCronSwitch)) {
                sendMsg.sendSms(recvMobile, String.format("%s Job在%s调度正常（生产）", jobName, new Date()), SMSType.OTHER_SMS);
            } else
                logger.info(String.format("cron预警短信已关闭：%s Job在%s调度正常", jobName, new Date()));
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
